//
//  AppDetailViewController.m
//  LimitFree
//
//  Created by lijinghua on 16/3/2.
//  Copyright © 2016年 lijinghua. All rights reserved.
//

#import "AppDetailViewController.h"
#import "AppDetailModel.h"
#import "ImageCollectionViewCell.h"
#import "NearbyAppModel.h"
#import "PhotoBrowseViewController.h"
#import "UMSocial.h"

@interface AppDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UMSocialUIDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *appTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *appDescLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeAndLevelLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *appImageCollectionView;
@property (weak, nonatomic) IBOutlet UITextView *appDescTextView;
@property (weak, nonatomic) IBOutlet UICollectionView *nearbyAppCollectionView;
@property (weak, nonatomic) IBOutlet UIButton *collectionButton;

@property(nonatomic)AppDetailModel *detailModel;

//应用图片的列表
@property(nonatomic)NSArray *appImageArray;

//附近的app的列表
@property(nonatomic)NSArray *nearByAppArray;
@end

@implementation AppDetailViewController

- (id)init{
    if (self = [super init]) {
        self.title = @"应用详情";
        self.navigationStyle = LFNavigationBackStyle;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.appImageCollectionView.backgroundColor = [UIColor clearColor];
    self.nearbyAppCollectionView.backgroundColor = [UIColor clearColor];
    
    //对于UICollectionView，必须注册自己使用的cell
    UINib *nib = [UINib nibWithNibName:@"ImageCollectionViewCell" bundle:nil];
    [self.appImageCollectionView registerNib:nib forCellWithReuseIdentifier:@"appImageCellId"];
    
    [self.nearbyAppCollectionView registerNib:nib forCellWithReuseIdentifier:@"nearbyCellId"];
    
    //下载app详情数据
    [self fetchAppDetailData];
    //下载附近的app的数据
    [self fetchNearbyAppData];
    
    //根据applictionId 来修改收藏按钮的状态
    [self updateCollectionButtonStatus];
}

- (void)updateCollectionButtonStatus{
   BOOL isExist = [[AppDataBaseManager sharedInstance] isAppExists:self.applicationId];
    if (isExist) {
        self.collectionButton.enabled = NO;
        [self.collectionButton setTitle:@"已收藏" forState:UIControlStateNormal];
    }
}

- (IBAction)doShareAction:(id)sender {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UMeng_AppKey
                                      shareText:@"1521 iOS 开发工程师"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToTencent,nil]
                                       delegate:self];
}

-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    if (response.responseCode == UMSResponseCodeSuccess) {
        NSLog(@"分享成功");
    }else{
        NSLog(@"分享失败");
    }
}

- (IBAction)doCollectionAction:(id)sender {
    //把app 详情信息保存到数据库
    [[AppDataBaseManager sharedInstance] insertAppInfo:self.detailModel];
    //把按钮变为不可点击状态
    self.collectionButton.enabled = NO;
    //按钮文字修改为已收藏
    [self.collectionButton setTitle:@"已收藏" forState:UIControlStateNormal];
}

- (IBAction)doDownloadAction:(id)sender {
    //需要跳转到appstore 让用户下载
    //openURL 打开一个应用或链接
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.detailModel.itunesUrl]];
}

#pragma mark - 网络数据获取
- (void)fetchAppDetailData{
    NSString *url =  [NSString stringWithFormat:kDetailUrl,self.applicationId];
    //使用网络引擎下载数据
    [[NetDataEngine sharedInstance] requestAppDetail:url success:^(id respondObject) {
        self.detailModel = [[AppDetailModel alloc]initWithDictionary:respondObject error:nil];
        //更新界面
        [self updateDetailInfoWith:self.detailModel];
        
    } falied:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)fetchNearbyAppData{
    [[NetDataEngine  sharedInstance] requestNearbyApp:^(id respondObject) {
        self.nearByAppArray = [NearbyAppModel parseRespondsData:respondObject];
        [self.nearbyAppCollectionView reloadData];
    } falied:^(NSError *error) {
        
    }];
}

- (void)updateDetailInfoWith:(AppDetailModel*)model{
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.iconUrl]];
    self.appTitleLabel.text = model.name;
    self.appDescLabel.text = [NSString stringWithFormat:@"原价:¥%@ 限免中 文件大小:%.2f",model.lastPrice,[model.fileSize floatValue]];
    self.typeAndLevelLabel.text = [NSString stringWithFormat:@"类型:%@ 评分:%@",model.categoryName,model.starOverall];
    
    self.appDescTextView.editable  = NO;
    self.appDescTextView.backgroundColor = [UIColor clearColor];
    self.appDescTextView.text = model.appDescription;
    //设置数据元
    self.appImageArray = model.photos;
    //显示图片列表的collectionView刷新
    [self.appImageCollectionView reloadData];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.appImageCollectionView) {
        return self.appImageArray.count;
    }else{
        return self.nearByAppArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.appImageCollectionView) {
        ImageCollectionViewCell *cell = [self.appImageCollectionView dequeueReusableCellWithReuseIdentifier:@"appImageCellId" forIndexPath:indexPath];
        PhotoModel *photoModel = self.appImageArray[indexPath.row];
        [cell.appIconImageView sd_setImageWithURL:[NSURL URLWithString:photoModel.smallUrl]];
        return cell;
    }else{
        ImageCollectionViewCell *cell = [self.nearbyAppCollectionView dequeueReusableCellWithReuseIdentifier:@"nearbyCellId" forIndexPath:indexPath];
        NearbyAppModel *model = self.nearByAppArray[indexPath.row];
        [cell.appIconImageView sd_setImageWithURL:[NSURL URLWithString:model.iconUrl]];
        return cell;
    }
}

//选中某一项的代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(collectionView == self.appImageCollectionView){
        //导航到图片预览的界面
        PhotoBrowseViewController *photoBrowseViewController = [[PhotoBrowseViewController alloc] init];
        photoBrowseViewController.photoArray = self.detailModel.photos;
        photoBrowseViewController.currentSelectIndex = indexPath.row;
        photoBrowseViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:photoBrowseViewController animated:YES];
    }else{
        //导航到应用详情界面
        NearbyAppModel *model = self.nearByAppArray[indexPath.row];
        if (model.applicationId) {
            AppDetailViewController *detailViewController = [[AppDetailViewController alloc]init];
            detailViewController.applicationId = model.applicationId;
            [self.navigationController  pushViewController:detailViewController animated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
